package com.mipo.mybatis.mysql.base;

import com.mipo.mybatis.mysql.base.CST;

import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * Created by cc on 2017/4/9.
 */
public class BaseServiceImpl<T> implements IBaseService<T> {


    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private BaseMapper<T> mapper;

    public void setMapper(BaseMapper m) {
        this.mapper = m;
    }


    @Autowired
    protected SqlSessionTemplate sqlSessionTemplate;


    @Override
    public long insert(T po) {
        return mapper.insert(po);
    }

    @Override
    public long batchInsert(List<T> list) {
        if (CollectionUtils.isEmpty(list)) {
            return -1;
        }
        if (list.size() > CST.CST_BATCH_INSERT_MXA_SIZE) {
            int insertCount = list.size() / CST.CST_BATCH_INSERT_MXA_SIZE;
            if (list.size() % CST.CST_BATCH_INSERT_MXA_SIZE > 0) {
                insertCount++;
            }
            for (int i = 0; i < insertCount; i++) {
                List<T> insertList = null;
                if (i == insertCount - 1) {
                    insertList = list.subList(i * CST.CST_BATCH_INSERT_MXA_SIZE, list.size());
                } else {
                    insertList = list.subList(i * CST.CST_BATCH_INSERT_MXA_SIZE, (i + 1) * CST.CST_BATCH_INSERT_MXA_SIZE);
                }
                mapper.batchInsert(insertList);
            }
        } else {
            return mapper.batchInsert(list);
        }
        return -2;
    }

    @Override
    public Integer delete(BaseDto dto) {
        return mapper.delete(dto);
    }

    @Override
    public Integer update(T po) {
        return mapper.update(po);
    }


    public long batchUpdate(Map<String,Object> param){
        return mapper.batchUpdate(param);
    }

    @Override
    public T get(BaseDto dto) {
        return mapper.get(dto);
    }

    @Override
    public T get(Long pkid) {
        return mapper.getOne(pkid);
    }

    @Override
    public List<T> list(BaseDto dto) {
        return mapper.list(dto);
    }

    @Override
    public List<T> listAll() {
        return mapper.topSizeList(CST.CST_BATCH_SEARCH_ALL_MXA_SIZE);
    }


    @Override
    public Pagination<T> splitList(BaseDto dto) {
        Pagination<T> page = new Pagination<T>();
        int total = mapper.getCount(dto);
        List<T> rows = mapper.getSplitList(dto);
        page.setRows(rows);
        page.setTotal(total);
        return page;
    }

    @Override
    public int getCount(BaseDto dto) {
        return mapper.getCount(dto);
    }

    @Override
    public List<T> getSplitList(BaseDto dto) {
        return mapper.getSplitList(dto);
    }


}
